//
//  FLAutoScollView.m
//  BaseRepo
//
//  Created by leo on 2018/8/9.
//  Copyright © 2018年 LEO. All rights reserved.
//

#import "FLAutoScollView.h"
#import "FLAutoScollViewCell.h"

#import "UIImageView+WebCache.h"

@interface FLAutoScollView ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UICollectionView *imageCollectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
///定时器
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger currentPage;

@end

@implementation FLAutoScollView

#pragma mark- life cycle
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self p_initialization];
    }
    return self;
}

- (void)dealloc {
    
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark- system method
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    //自定义cell
    if (self.registerClass && [self.delegate respondsToSelector:@selector(collectionView:indexPathForCell:)]) {
         return [self.delegate collectionView:collectionView indexPathForCell:indexPath];
    }else {
        //默认的cell 只有一个图片控件
        FLAutoScollViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([FLAutoScollViewCell class]) forIndexPath:indexPath];
        NSString *imageStr = self.dataSource[indexPath.row];
        if ([imageStr hasPrefix:@"http"] || [imageStr hasPrefix:@"https"]) {
            [cell.backImageView sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:self.placeHolderImage];
        }else {
            cell.backImageView.image = [UIImage imageNamed:imageStr];
        }
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger index = collectionView.contentOffset.x / self.bounds.size.width;
    if ([self.delegate respondsToSelector:@selector(autoScrollViewDidSelectedItemAtIndex:)]) {
        if (self.loop && self.dataSource.count > 1) {
            [self.delegate autoScrollViewDidSelectedItemAtIndex:index - 1];

        }else {
            [self.delegate autoScrollViewDidSelectedItemAtIndex:index];
        }
    }
}


#pragma mark- scrollView delegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView  {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.isAutoScroll) {
        self.autoScrollTimeInterval = self.autoScrollTimeInterval;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 2 0 1 2 0
    NSInteger page = scrollView.contentOffset.x / self.bounds.size.width;
    if (self.loop) {
//        FLLog(@"滚动到：%zd",page);
        if (page == 0) {//滚动到左边
            [scrollView setContentOffset:CGPointMake(scrollView.bounds.size.width * (self.dataSource.count - 2), 0) animated:NO];
            self.pageControl.currentPage = self.dataSource.count - 2;
        
        }else if (page == self.dataSource.count - 1){//滚动到右边
            [scrollView setContentOffset:CGPointMake(scrollView.bounds.size.width, 0) animated:NO];
            self.pageControl.currentPage = 0;

        }else{
            self.pageControl.currentPage = page - 1;
        }
        
    }else {
        
        self.pageControl.currentPage = page;
    }
}

#pragma mark- private method
//初始化
- (void)p_initialization {
    [self addSubview:self.imageCollectionView];
    [self addSubview:self.pageControl];
    //默认开启自动滚动
    self.isAutoScroll = YES;
}

//自动滚动的方法
- (void)autoScroll:(NSTimer *)timer {
    self.currentPage = self.imageCollectionView.contentOffset.x / self.bounds.size.width + 1;
    if (self.loop) {
        //最后一张的时候复原
        if (self.currentPage == self.dataSource.count - 1) {
            self.currentPage = 1;
        }
        self.pageControl.currentPage = self.currentPage - 1;

    }else {
        //不是循环的时候滚动最后一张
        if (self.currentPage == self.dataSource.count - 1) {
            [self.timer invalidate];
            self.timer = nil;
        }
        self.pageControl.currentPage = self.currentPage;

    }
    [self.imageCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentPage inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}

#pragma mark- public medthod
- (void)refreshScrollView {
    self.imageCollectionView.scrollEnabled = self.dataSource.count <= 1? NO : YES;
    if (self.registerClass) {
        [self.imageCollectionView registerClass:self.registerClass forCellWithReuseIdentifier:NSStringFromClass(self.registerClass)];
    }
    
    if (self.dataSource.count <= 1) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    if (!self.isAutoScroll) {
        [self.timer invalidate];
        self.timer = nil;
    }
    [self.imageCollectionView reloadData];
}

- (void)setImageArray:(NSArray *)imageArray {
    self.dataSource = imageArray.mutableCopy;
    //开启无限循环
    if (self.loop && imageArray.count > 1) {
        [self.dataSource addObject:imageArray.firstObject];
        [self.dataSource insertObject:imageArray.lastObject atIndex:0];
        [self.imageCollectionView setContentOffset:CGPointMake(self.bounds.size.width, 0) animated:NO];
    }
    self.pageControl.numberOfPages = imageArray.count;
    //创建定时器自动滚动
    self.autoScrollTimeInterval = self.dataSource.count > 1? 3 : 0.f;
}

- (NSArray *)imageArray {
    return self.dataSource.copy;
}

- (void)setHiddenPageControl:(BOOL)hiddenPageControl {
    _hiddenPageControl = hiddenPageControl;
    self.pageControl.hidden = hiddenPageControl;
}

- (void)setAutoScrollTimeInterval:(NSTimeInterval)autoScrollTimeInterval {
    _autoScrollTimeInterval = autoScrollTimeInterval;
    //大于0才创建时间自动滚动
    if (_autoScrollTimeInterval > 0) {
        if (self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
        self.timer = [NSTimer timerWithTimeInterval:self.autoScrollTimeInterval target:self selector:@selector(autoScroll:) userInfo:nil repeats:YES];
        
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

    }
    
}

- (void)setColorForSelectPage:(UIColor *)colorForSelectPage {
    self.pageControl.currentPageIndicatorTintColor = colorForSelectPage;
}

- (void)setDefaulColorForPage:(UIColor *)defaulColorForPage {
    self.pageControl.pageIndicatorTintColor = defaulColorForPage;
}
#pragma mark- getter and setter
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}


- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 30, self.bounds.size.width, 22)];
        _pageControl.hidesForSinglePage = YES;
    }
    return _pageControl;
}

- (UICollectionView *)imageCollectionView {
    if (!_imageCollectionView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
        flow.minimumLineSpacing = 0;
        flow.minimumInteritemSpacing = 0;
        flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flow.itemSize = self.bounds.size;
        _imageCollectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flow];
        _imageCollectionView.showsHorizontalScrollIndicator = NO;
        _imageCollectionView.showsVerticalScrollIndicator = NO;
        _imageCollectionView.delegate = self;
        _imageCollectionView.dataSource = self;
        [_imageCollectionView registerClass:[FLAutoScollViewCell class] forCellWithReuseIdentifier:NSStringFromClass([FLAutoScollViewCell class])];
        _imageCollectionView.pagingEnabled = YES;
        _imageCollectionView.showsVerticalScrollIndicator = NO;
        _imageCollectionView.showsHorizontalScrollIndicator = NO;
        }
    return _imageCollectionView;
}


@end
